package socketserver;

import net.ClientCommunicator;
import messages.LoginMessage;
import messages.Message;
import messages.QuitMessage;
import messages.RegisterMessage;
import user.User;
import core.Controller;

/**
 * SocketClientHandler class.
 * 
 * Client-handler specific for sockets.
 */
public class SocketClientHandler  implements Runnable {
	
	/**
	 * Constructor
	 * 
	 * Subscribes to the Controller events.
	 * 
	 * @param socket The socket that allows communication with the client.
	 */
	public SocketClientHandler(SocketClientCommunicator communicator) {
		this.controller = Controller.getInstance();
		this.communicator = communicator;
		System.out.println("New client logged");
	}

	
	public void run() {
		User user = authenticate();
		
		if (user == null)
			return;
		
		while (true) {			
			Message message = user.receive();
						
			if (message == null)
				break;
						
			controller.getMessageManager().getMessageConsumer().putMessage(message, user);
			
			if (message instanceof QuitMessage)
				break;
		}
	}
	
	
	private User authenticate() {
		User user = null;
		
		Message message = this.communicator.receive();
		if (message instanceof LoginMessage) {
			user = this.controller.authenticate((LoginMessage) message, this.communicator);
		} else if (message instanceof RegisterMessage) {
			user = this.controller.register((RegisterMessage) message, this.communicator);
		}
		
		return user;
	}
	
	protected Controller controller; 			// The main Controller
	protected ClientCommunicator communicator;  // The Client associated with this handler
}
